package com.bree.erp.service.stateless;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import com.bree.erp.entity.Inventory;
import com.bree.erp.entity.MasterItem;
import com.bree.erp.entity.Unit;
import com.bree.erp.jsf.vo.InventoryDT;
import com.bree.erp.service.InventoryService;
import com.bree.erp.service.InventoryWrapperService;

@Stateless
public class InventoryWrapperServiceBean implements InventoryWrapperService {
	
	@EJB
	private InventoryService delegate;
	
	private List<InventoryDT> cached;

	@Override
	public InventoryDT read(String id) {
		if(cached == null) {
			list();
		}
		
		InventoryDT template = new InventoryDT(id);
		int idx = cached.indexOf(template);
		return idx < 0 ? null : cached.get(idx);
	}

	@Override
	public Collection<InventoryDT> list() {
		Collection<Inventory> list = delegate.list();
		
		 cached = new ArrayList<InventoryDT>();
				
		for(Inventory item : list) {
			
			Map<Unit, Double> unitsLeft = item.getUnits();
			Map<Unit, Double> unitThreashold = item.getUnits(); 
			for(Unit unit : unitsLeft.keySet()) {
				Double quantity = unitsLeft.get(unit);
				Double threashold = unitThreashold.get(unit);
				
				String id = item.getId() + ":" + unit.getCode();
					
				cached.add(new InventoryDT(id, item, unit, quantity, threashold));
			}
		}
		
		return cached;
	}

	@Override
	public Inventory create(MasterItem entity) {
		return delegate.create(entity);
	}


}
